package com.ruoyi.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;

@Component
public class WechatMsg {
    /**
     * 获取token
     *
     * @return token
     */
    public String getToken() {
        // 授予形式
        String grant_type = "client_credential";
        //应用ID
        String appid = "XXXXXXXXXXXXXXXXXXXXXXXXX";
        //密钥
        String secret = "XXXXXXXXXXXXXXXXXXXXXXXXX";
        // 接口地址拼接参数
        String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appid
                + "&secret=" + secret;
        String tokenJsonStr = doGetPost(getTokenApi, "GET", null);
        JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
        String token = tokenJson.get("access_token").toString();
        System.out.println("获取到的TOKEN : " + token);
        return token;
    }
    /***
     * 群发文本消息
     * @param token
     */
    public Integer GroupMessage(String token,String content) {
        // 接口地址
        String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+token;
        //整体参数map
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //相关map
        Map<String, Object> dataMap1 = new HashMap<String, Object>();
        Map<String, String> dataMap2 = new HashMap<String, String>();
        dataMap1.put("is_to_all",true);//用于设定是否向全部用户发送，值为true或false，选择true该消息群发给所有用户，选择false可根据tag_id发送给指定群组的用户
        dataMap1.put("tag_id",1);//群发到的标签的tag_id，参见用户管理中用户分组接口，若is_to_all值为true，可不填写tag_id
        dataMap2.put("content",content);//要推送的内容
        paramMap.put("filter",dataMap1);//用于设定图文消息的接收者
        paramMap.put("text", dataMap2);//文本内容
        paramMap.put("msgtype","text");//群发的消息类型，图文消息为mpnews，文本消息为text，语音为voice，音乐为music，图片为image，视频为video，卡券为wxcard
        String back=doGetPost(sendMsgApi,"POST",paramMap);
        System.out.println("群发返回:"+back);
        JSONObject jsonObject =JSONObject.parseObject(back);//String转JSONObject，
        Integer re=jsonObject.getInteger("errcode");
        return re;
    }
    /**
     * 调用接口 post
     * @param apiPath
     */
    public String doGetPost(String apiPath,String type,Map<String,Object> paramMap){
        OutputStreamWriter out = null;
        InputStream is = null;
        String result = null;
        try{
            URL url = new URL(apiPath);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(type) ; // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            if(type.equals("POST")){
                out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                out.append(JSON.toJSONString(paramMap));
                out.flush();
                out.close();
            }
            // 读取响应
            is = connection.getInputStream();
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                result = new String(data, "UTF-8"); // utf-8编码
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }
}